import React, { useState, useEffect } from 'react';
import { X, Save, Edit3, FileText, RefreshCw } from 'lucide-react';

interface MemoModalProps {
  isOpen: boolean;
  onClose: () => void;
  sessionId: string;
  sessionTitle: string;
}

interface MemoData {
  memo: string;
  memo_created_at?: string;
  memo_updated_at?: string;
}

const MemoModal: React.FC<MemoModalProps> = ({
  isOpen,
  onClose,
  sessionId,
  sessionTitle
}) => {
  const [memoContent, setMemoContent] = useState('');
  const [isEditing, setIsEditing] = useState(false);
  const [isSaving, setSaving] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isRegenerating, setIsRegenerating] = useState(false);
  const [lastUpdated, setLastUpdated] = useState<string | null>(null);
  const [userMessageCount, setUserMessageCount] = useState(0);

  // 加载备忘录
  const loadMemo = async () => {
    if (!sessionId) return;
    
    try {
      setIsLoading(true);
      const response = await fetch(`/api/sessions/${sessionId}/memo`);
      const data = await response.json();
      
      if (response.ok && data.success) {
        setMemoContent(data.data.memo || '');
        setLastUpdated(data.data.memo_updated_at || data.data.memo_created_at || null);
        setUserMessageCount(data.data.user_message_count || 0);
      }
    } catch (error) {
      console.error('加载备忘录失败:', error);
    } finally {
      setIsLoading(false);
    }
  };

  // 保存备忘录
  const saveMemo = async () => {
    try {
      setSaving(true);
      const response = await fetch(`/api/sessions/${sessionId}/memo`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ memo: memoContent })
      });
      
      const data = await response.json();
      
      if (response.ok && data.success) {
        setLastUpdated(data.data.memo_updated_at);
        setIsEditing(false);
      } else {
        alert('保存备忘录失败: ' + (data.message || data.detail || '未知错误'));
      }
    } catch (error) {
      console.error('保存备忘录失败:', error);
      alert('保存备忘录失败，请检查网络连接');
    } finally {
      setSaving(false);
    }
  };

  // 重新生成备忘录
  const regenerateMemo = async () => {
    try {
      setIsRegenerating(true);
      const response = await fetch(`/api/sessions/${sessionId}/memo/regenerate`, {
        method: 'POST'
      });
      
      const data = await response.json();
      
      if (response.ok && data.success) {
        setMemoContent(data.data.memo);
        setLastUpdated(data.data.memo_updated_at);
        setIsEditing(false);
      } else {
        const errorMessage = data.message || data.detail || '未知错误';
        if (errorMessage.includes('对话轮次不足')) {
          alert('⚠️ 无法生成备忘录\n\n' + errorMessage + '\n\n💡 提示：继续与AI对话，当达到足够的对话轮次后即可生成备忘录。');
        } else {
          alert('❌ 重新生成备忘录失败\n\n' + errorMessage);
        }
      }
    } catch (error) {
      console.error('重新生成备忘录失败:', error);
      alert('重新生成备忘录失败，请检查网络连接');
    } finally {
      setIsRegenerating(false);
    }
  };

  // 打开Modal时加载备忘录
  useEffect(() => {
    if (isOpen && sessionId) {
      loadMemo();
    }
  }, [isOpen, sessionId]);

  // 关闭Modal时重置状态
  const handleClose = () => {
    setIsEditing(false);
    onClose();
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[80vh] flex flex-col">
        {/* Modal 头部 */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <div className="flex items-center gap-3">
            <FileText className="w-5 h-5 text-blue-600" />
            <div>
              <h2 className="text-lg font-semibold text-gray-900">会话备忘录</h2>
              <p className="text-sm text-gray-500 truncate max-w-md">{sessionTitle}</p>
            </div>
          </div>
          <button
            onClick={handleClose}
            className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
          >
            <X className="w-5 h-5 text-gray-500" />
          </button>
        </div>

        {/* Modal 内容 */}
        <div className="flex-1 p-6 overflow-y-auto">
          {isLoading ? (
            <div className="flex items-center justify-center py-8">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
              <span className="ml-3 text-gray-600">加载中...</span>
            </div>
          ) : (
            <div>
              {/* 备忘录内容区域 */}
              <div className="mb-4">
                <div className="flex items-center justify-between mb-3">
                  <label className="block text-sm font-medium text-gray-700">
                    备忘录内容
                  </label>
                  {lastUpdated && (
                    <span className="text-xs text-gray-500">
                      最后更新：{new Date(lastUpdated).toLocaleString()}
                    </span>
                  )}
                </div>
                
                {isEditing ? (
                  <textarea
                    value={memoContent}
                    onChange={(e) => setMemoContent(e.target.value)}
                    placeholder="记录关于这次对话的重要信息、要点、决策等..."
                    className="w-full h-64 p-4 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-none"
                    autoFocus
                  />
                ) : (
                  <div className="min-h-64 p-4 border border-gray-200 rounded-lg bg-gray-50">
                    {memoContent ? (
                      <pre className="whitespace-pre-wrap text-sm text-gray-700 font-sans leading-relaxed">
                        {memoContent}
                      </pre>
                    ) : (
                      <div className="flex flex-col items-center justify-center h-full text-gray-500">
                        <FileText className="w-12 h-12 mb-3 text-gray-300" />
                        <p className="text-sm">暂无备忘录内容</p>
                        <p className="text-xs text-gray-400 mt-1">点击编辑按钮开始记录</p>
                      </div>
                    )}
                  </div>
                )}
              </div>

              {/* 提示信息 */}
              <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <div className="flex">
                  <div className="flex-shrink-0">
                    <svg className="h-5 w-5 text-blue-400" viewBox="0 0 20 20" fill="currentColor">
                      <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" />
                    </svg>
                  </div>
                  <div className="ml-3">
                    <p className="text-sm text-blue-800">
                      <strong>💡 小提示：</strong> 备忘录会自动作为上下文提供给AI，帮助它更好地理解对话背景和历史重点。
                    </p>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Modal 底部 */}
        <div className="flex items-center justify-between p-6 border-t border-gray-200">
          <div className="flex gap-2">
            {!isEditing && (
              <button
                onClick={regenerateMemo}
                disabled={isRegenerating || userMessageCount < 3}
                className={`inline-flex items-center gap-2 px-4 py-2 rounded-lg transition-colors ${
                  userMessageCount < 3 
                    ? 'bg-gray-300 text-gray-500 cursor-not-allowed' 
                    : 'bg-green-600 text-white hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed'
                }`}
                title={userMessageCount < 3 ? `需要至少3轮对话才能生成备忘录（当前${userMessageCount}轮）` : ''}
              >
                <RefreshCw className={`w-4 h-4 ${isRegenerating ? 'animate-spin' : ''}`} />
                {isRegenerating ? 'AI生成中...' : 
                 userMessageCount < 3 ? `AI生成 (${userMessageCount}/3轮)` : 'AI自动生成'}
              </button>
            )}
          </div>

          <div className="flex gap-3">
            <button
              onClick={handleClose}
              className="px-4 py-2 text-gray-600 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors"
            >
              关闭
            </button>
            {isEditing ? (
              <>
                <button
                  onClick={() => setIsEditing(false)}
                  className="px-4 py-2 text-gray-600 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors"
                >
                  取消
                </button>
                <button
                  onClick={saveMemo}
                  disabled={isSaving}
                  className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                >
                  <Save className="w-4 h-4" />
                  {isSaving ? '保存中...' : '保存'}
                </button>
              </>
            ) : (
              <button
                onClick={() => setIsEditing(true)}
                className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
              >
                <Edit3 className="w-4 h-4" />
                编辑
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default MemoModal;